<?php
/**
 * 定时统计每天扫码
 * @author guoxiaoyong
 */
namespace console\controllers;

use yii\console\Controller;
use bc\ar\MActiveRecord;

/**
 * Qrcode controller
 */
class QrcodeController extends Controller
{
	public function actionIndex()
	{
		set_time_limit(0);
		$model = new \bc\model\qrcode\ScanModel();
		
		$dao = new MActiveRecord();
		$sql = 'select qid, scene_id, subscribe, scan, scene from `wxch_qr` where type = \'qr\'';
		
		$result = $dao->getDb()->createCommand($sql)->queryAll();
		
		$last_day_time = strtotime('-1 day', strtotime(date('Y-m-d')));
		
		$current_time = strtotime(date('Y-m-d'));
		
		if($result)
		{
			foreach ($result as $key=>$item)
			{
				$rowSql = 'select * from bc_qrcode_scan where scene_id = ' . $item['qid'] . ' AND create_time = ' . $current_time;
				$row = $dao->getDb()->createCommand($rowSql)->queryOne();
				if(!$row)
				{
					$create_time = $current_time;
					$scene_id = $item['qid'];
					
					//新加当前日期的
					$preSql = 'select * from bc_qrcode_scan where scene_id = ' . $item['qid'] . ' AND create_time = ' . $last_day_time;
					$preRow = $dao->getDb()->createCommand($preSql)->queryOne();
					
					if($preRow)
					{
						$subscribe = $item['subscribe'] - $preRow['total_subscribe'];
						$subscribe = $subscribe < 0 ? 0 : $subscribe;
						
						$scan = $item['scan'] - $preRow['total_scan'];
						$scan = $scan < 0 ? 0 : $scan;
					}
					else 
					{
						$subscribe = $item['subscribe'] ;
						$scan = $item['scan'];
					}
					
					$insertSql = "insert bc_qrcode_scan (scene_id, subscribe, scan, total_subscribe, total_scan, create_time) values ({$scene_id}, {$subscribe}, {$scan},{$item['subscribe']}, {$item['scan']}, {$create_time})";
					$dao->getDb()->createCommand($insertSql)->execute();					
					
				}
				
			}
		}
		echo 'done';
		
	}
}  

